#include <iostream>
#include <string>
#include "userPresenter.h"
#include "json/json.h"

#include "UserDao.h"
#include "common.h"


#define ERRCD_NOACCOUNT "-2"
#define ERRCD_PASSWDERR "-1"
using namespace std;
void userRegister(string data, ResData& res_data);
void userLogin(string data, ResData& res_data);
UserDao *userDao;
moduleHandler user_cmds[] = {
    {"01", userRegister},
    {"02", userLogin}
};

void userRegister(string data, ResData& res_data){
    
}

void userLogin(string data, ResData& res_data){

    userBean *muserBean, cxuser;
    Json::Value root;
    Json::String  jsError;
    Json::CharReaderBuilder readerBuilder;
    std::unique_ptr<Json::CharReader>reader(readerBuilder.newCharReader());

    if(!reader->parse(data.c_str(), data.c_str()+data.length(), &root, &jsError)){
        res_data.resp_code = ERRCD_NOACCOUNT;
        goto err;
    }

    if(!root["userName"].isNull() && !root["userPass"].isNull()){
        string userName = root["userName"].asString();
        string userPass = root["userPass"].asString();
        muserBean = new userBean(userName, userPass, "");

        userDao->getUser(muserBean, cxuser);

        /* 查无账号 */
        if(cxuser.getUserName() == ""){
            res_data.resp_code = ERRCD_NOACCOUNT;
            goto err;
        }

        /* 密码错误 */
        if(cxuser.getUserName() != userName
           || cxuser.getUserPass() != userPass){

            res_data.resp_code = ERRCD_PASSWDERR;
            goto err;
        }else{


            //判断是否注册
            string sid;
            if(userDao->isUserRegister(cxuser.getToken(), sid)){

                /* 成功 */
                res_data.resp_code = ERRCD_PASS;
                res_data.resp_data = "\"sid\":\"" + sid + "\"";

            }else{

                /* 查无账号 */
                res_data.resp_code = ERRCD_NOACCOUNT;
                goto err;
            }
        }

    }

err:
    if(muserBean != nullptr){
        free(muserBean);
        muserBean = nullptr;
    }
}


userPresenter::userPresenter()
{
    userDao = UserDao::getInstance();
}

userPresenter::~userPresenter()
{
}

void userPresenter::userMsgHandler(string cmd, string data, ResData& outData){
    cout << "subCmd: " << cmd << endl;
    cout << "user: " << data << endl;

    int i = 0;

    if(cmd.empty() || data.empty()){
        return;
    }

    for (i = 0; !user_cmds[i].cmd.empty(); ++i)
    {
        if (cmd != user_cmds[i].cmd)
            continue;
        break;
    }

    user_cmds[i].func(data, outData);
}